import re
import sqlite3
import os
import logging
from django.http import HttpResponse
from django.conf import settings
import json
import random

oozie_home='/export/datamarket/oozie/oozie-4.3.1/bin/'
logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S')

def resume(request):

	if request.method == 'POST':
		try:	
			received_json_data=json.loads(request.body.decode().replace("'", "\""))
			logging.info("\n\n\n\t"+str(received_json_data)+"\n\n")
			jobid=received_json_data['jobid'].strip()
			
			db_path = os.path.normpath('/export/datamarket/OozieProperties/oozie_project/db.sqlite3') 
			db = sqlite3.connect(db_path) 
			# 通过cursor创建游标
			cursor = db.cursor()
			sql_jobid="select mission_val from oozie_configuration where jobid ={}".format(jobid)
			cursor.execute(sql_jobid)
			mission_val=cursor.fetchall()
			mission_val=mission_val[0][0]
			#通过oozie查找要启用的job的信息
			randomNum=os.popen('echo -n `date +%s%N`').read()
			jobIDinfoFile='jobIDinfo'+str(randomNum)+str(random.uniform(1, 24))
			jobidFile='jobid'+str(randomNum)+str(random.uniform(1, 24))
			os.system(oozie_home+"oozie jobs -localtime -filter 'name={}' -jobtype coordinator -len 1 > {}".format(mission_val,jobIDinfoFile))
			os.system("sed -i '1d' {}".format(jobIDinfoFile))
			os.system("cat ".format(jobIDinfoFile)+" |awk -F ' ' '{print$1}' >"+jobidFile)
			os.system("sed -i '1d' {}".format(jobidFile))
			os.system("sed -i '2d' {}".format(jobidFile))
			coordinatorJobid=os.popen("cat {}".format(jobidFile)).read().strip()
			os.remove("{}".format(jobIDinfoFile))
			os.remove("{}".format(jobidFile))
			os.system(oozie_home+"oozie job -resume {}".format(coordinatorJobid))
			#修改sqlite中job为启用
			sql_forbid="update oozie_configuration set status='' where jobid='{}'".format(jobid)
			cursor.execute(sql_forbid)
			logging.info("修改sqlite中jobid为"+jobid+"启用")
			cursor.close()
			db.commit()
			db.close()
			result={"result":mission_val+"启用成功","code":"0"}
			logging.info(result)
			return HttpResponse(json.dumps(result,ensure_ascii=False), content_type="application/json;charset=utf-8")
		except:
			result={"result":"没有启用","code":"1"}
			logging.info(result)
			return HttpResponse(json.dumps(result,ensure_ascii=False), content_type="application/json;charset=utf-8")
	else:
		pass
